const router = require('koa-router')();
const readIMG = require('../middleWares/responseImg.js')
const a = require('../middleWares/cropperImg.js')
const crop = require('../middleWares/crop')
var fs = require('fs');
var path = require('path')
let md5 = require('md5')
let cropInstance = new crop()
cropInstance.init()
router.get('/img', async (ctx, next) => {
  let req = ctx.request
  // 通过请求路径生成要返回的文件名
  let fileName = md5(req.url)
  let resimg = '/img/images/'+fileName+'.png'

  const exists = fs.existsSync(path.join(__dirname,'../public/images/'+fileName+'.png'))
  if(exists){
    let resimg = '/img/images/'+fileName+'.png'
    // console.log(exists)
    ctx.body= { "img": resimg}
  } else {
    await cropInstance.getCrop(ctx)
    ctx.body= { "img": resimg}
  }
})


router.get('/string', async (ctx, next) => {
  ctx.response.set('token', 'abc')
  ctx.body = 'ok'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
